#include "vxpinbutton.h"



VxPinButton::VxPinButton(QWidget * parent, State state) : QWidget(parent)
{
	//
	setFixedSize(18, 20);
	QStackedLayout * layout = new QStackedLayout(this);

	QWidget * widgets[2];

	widgets[PINNED] = new QWidget();
	widgets[RELEASED] = new QWidget();

	layout->addWidget(widgets[PINNED]);
	QLabel * labelMovement = new QLabel(widgets[PINNED]);
	labelMovement->setPixmap(QPixmap(":/images/pushpin_pinned.png"));

	layout->addWidget(widgets[RELEASED]);
	QLabel * labelGuids = new QLabel(widgets[RELEASED]);
	labelGuids->setPixmap(QPixmap(":/images/pushpin_free.png"));

	connect(this, SIGNAL(stateChanged(int)), layout, SLOT(setCurrentIndex(int)));

	//
	QStateMachine * machine = new QStateMachine();

	QState * statePinned = new QState();
	statePinned->assignProperty(this, "state", PINNED);

	QState * stateReleased = new QState();
	stateReleased->assignProperty(this, "state", RELEASED);

	machine->addState(statePinned);
	machine->addState(stateReleased);

	QMouseEventTransition * switchedToPinned = new QMouseEventTransition(this,
											QEvent::MouseButtonRelease, Qt::LeftButton);
	switchedToPinned->setTargetState(statePinned);

	QMouseEventTransition * switchedToReleased = new QMouseEventTransition(this,
											QEvent::MouseButtonRelease, Qt::LeftButton);
	switchedToReleased->setTargetState(stateReleased);

	statePinned->addTransition(switchedToReleased);
	stateReleased->addTransition(switchedToPinned);

	switch (state){
	case PINNED:
		machine->setInitialState(statePinned);
		break;
	case RELEASED:
		machine->setInitialState(stateReleased);
		break;
	}

	machine->start();

	connect(this, SIGNAL(stateChanged(int)), layout, SLOT(setCurrentIndex(int)));


}



void VxPinButton::_setState(State state)
{
	if (_state == state){
		return;
	}
	_state = state;

	emit stateChanged(_state);

	switch(_state){

	case PINNED:
		emit pinned();
		break;

	case RELEASED:
		emit released();
		break;
	}
};

